import { _decorator, Component, Node, Sprite } from 'cc';
import { EnemyFrameAnimType, EnemyFrameInfo } from './Enemy/EnemyController';
import { EnemyFrameController } from './Enemy/EnemyFrameController';
const { ccclass, property } = _decorator;

@ccclass('FrameComponent')
export class FrameComponent extends Component {

    @property(Node)
    public bodyNode: Node = null;
    @property(Node)
    public animNode: Node = null;

    public _enemyFrameController: EnemyFrameController = null;

    public frameInfoList: Array<EnemyFrameInfo> = [];
    public curAnimInfo: EnemyFrameInfo;

    public bodySprite: Sprite;
    public curAttackInterval: number = 1;
    public attackInterval: number = 1;
    public _isAttack: boolean = false;

    async onLoad(): Promise<void> {
        this.bodySprite = this.animNode.getComponent(Sprite);
        //this.bodySprite.spriteFrame = null;
    }

    onEnable(): void {
        if (this._enemyFrameController == null) {
            this._enemyFrameController = this.animNode.getComponent(EnemyFrameController);
            this._enemyFrameController.completeListener = this.OnCompleteListener.bind(this);
        }
        this.onChildInit();
        this.PlayFrameAnim(EnemyFrameAnimType.Run);
    }

    onChildInit() {

    }

    update(deltaTime: number) {
        // this.CheckAttackTower();
        // if (this._isAttack) {
        //     this.curAttackInterval -= deltaTime;
        //     this.OnAttack(this.curAttackInterval);
        // }
    }

    UpdateCurAnimInfo(type: EnemyFrameAnimType) {
        let animInfo = null;
        for (let index = 0; index < this.frameInfoList.length; index++) {
            const element = this.frameInfoList[index];
            if (element.animType == type) {
                animInfo = element;
                break;
            }
        }
        return animInfo;
    }

    PlayFrameAnim(type: EnemyFrameAnimType) {
        if (this.curAnimInfo == null || type != this.curAnimInfo.animType) {
            let animInfo = this.UpdateCurAnimInfo(type);
            if (animInfo) {
                this.curAnimInfo = animInfo;
                this.curAttackInterval = 3;
                this._enemyFrameController.UpdateAnimInfo(this.curAnimInfo.speed, this.curAnimInfo.rootPath, this.curAnimInfo.frameName, this.curAnimInfo.startIndex, this.curAnimInfo.endIndex, this.curAnimInfo.isLoop);
            }
        }
    }

    OnCompleteListener(animName) {
        this.curAttackInterval = 1;
        this.PlayFrameAnim(EnemyFrameAnimType.Idle);
    }

    CheckAttackTower() {
        if (this._isAttack) {

        }
        else {

        }
    }

    OnAttack(interval: number) {
        if (interval <= 0) {
            this.PlayFrameAnim(EnemyFrameAnimType.Attack);
        }
    }
}


